﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace WSS.Pub
{
    public static class ClsExtends
    {
        // Methods
        public static string DataTableToJson(string jsonName, DataTable dt)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    builder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        builder.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < (dt.Columns.Count - 1))
                        {
                            builder.Append(",");
                        }
                    }
                    builder.Append("}");
                    if (i < (dt.Rows.Count - 1))
                    {
                        builder.Append(",");
                    }
                }
            }
            builder.Append("]}");
            return builder.ToString();
        }

        public static DateTime? GetDate(this IDictionary<string, object> dictionary, string key)
        {
            DateTime? nullable = null;
            key = key.ToUpper();
            if (dictionary.ContainsKey(key))
            {
                string str = Utils.GetString(dictionary[key]);
                nullable = (((str == "0001-01-01") || (str == "1900-01-01")) || (str == "")) ? nullable : new DateTime?(Convert.ToDateTime(dictionary[key]));
            }
            return nullable;
        }

        public static decimal GetDec(this IDictionary<string, object> dictionary, string key)
        {
            key = key.ToUpper();
            if (dictionary.ContainsKey(key))
            {
                return ((Utils.GetString(dictionary[key]) == "") ? 0M : Convert.ToDecimal(dictionary[key]));
            }
            return 0M;
        }

        public static string GetFormatValueString(this IDictionary<string, object> dictionary, string formatString)
        {
            return dictionary.GetFormatValueString(formatString, null);
        }

        public static string GetFormatValueString(this IDictionary<string, object> dictionary, string formatString, string captureRule)
        {
            IDictionary<string, string> dictionary2 = FormatParser.CaptureFormatKey(formatString, captureRule);
            if (dictionary2.Count > 0)
            {
                foreach (KeyValuePair<string, string> pair in dictionary2)
                {
                    if (dictionary.ContainsKey(pair.Key))
                    {
                        formatString = formatString.Replace(pair.Value, Utils.GetString(dictionary[pair.Key]));
                    }
                }
                return formatString;
            }
            formatString = Utils.GetString(dictionary[formatString.ToUpper()]);
            return formatString;
        }

        public static object GetObject(this IDictionary<string, object> dictionary, string key)
        {
            key = key.ToUpper();
            if (dictionary.ContainsKey(key))
            {
                return dictionary[key];
            }
            return null;
        }

        public static object GetPropreryValue(this object o, string propertyName)
        {
            if (o != null)
            {
                PropertyInfo[] infoArray = o.GetPublic_Instance_DeclaredOnly_PropertyInfo();
                foreach (PropertyInfo info in infoArray)
                {
                    if (info.Name.ToUpper() == propertyName.ToUpper())
                    {
                        return info.GetValue(o, null);
                    }
                }
            }
            return null;
        }

        public static PropertyInfo[] GetPublic_Instance_DeclaredOnly_PropertyInfo(this object o)
        {
            return o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        }

        public static PropertyInfo[] GetPublic_Instance_PropertyInfo(this object o)
        {
            return o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }

        public static string GetString(this IDictionary<string, string> dictionary, string key)
        {
            key = key.ToUpper();
            if (dictionary.ContainsKey(key))
            {
                return dictionary[key];
            }
            return null;
        }

        public static bool HasProperty(this object o, string propertyName)
        {
            if (o != null)
            {
                PropertyInfo[] infoArray = o.GetPublic_Instance_DeclaredOnly_PropertyInfo();
                foreach (PropertyInfo info in infoArray)
                {
                    if (info.Name.ToUpper() == propertyName.ToUpper())
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static bool IsDateTime(this object o)
        {
            return o.IsDateTime(false);
        }

        public static bool IsDateTime(this object o, bool strictly)
        {
            DateTime time;
            if (strictly)
            {
                Regex regex = new Regex(@"^(19|20)[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])\s*([0-1]?\d|2[0-3])?(:[0-5]?\d)?(:[0-5]?\d)?$");
                return regex.IsMatch(Utils.GetString(o).Trim());
            }
            return DateTime.TryParse(Utils.GetString(o), out time);
        }

        public static bool IsDecimal(this object o)
        {
            decimal num;
            bool flag = decimal.TryParse(o.ToString(), out num);
            return flag;
        }

        public static bool IsNumeric(this object o)
        {
            int num;
            bool flag = false;
            if (int.TryParse(o.ToString(), out num))
            {
                if (o.ToString().Length == 1)
                {
                    return true;
                }
                if (o.ToString().Length > 1)
                {
                    flag = !o.ToString().StartsWith("0");
                }
            }
            return flag;
        }

        public static JsonResult JsonBig(this ControllerBase controller, object data)
        {
            JsonResult2 result = new JsonResult2();
            result.Data = data;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public static IDictionary<string, object> Merger(this IDictionary<string, object> dictionary, object o)
        {
            return dictionary.Merger(o, true);
        }

        public static IDictionary<string, string> Merger(this IDictionary<string, string> dictionary, object o)
        {
            return dictionary.Merger(o, false);
        }

        public static IDictionary<string, object> Merger(this IDictionary<string, object> dictionary, object o, bool nullValueAsKey)
        {
            return dictionary.Merger(o, nullValueAsKey, ECase.NORMAL);
        }

        public static IDictionary<string, string> Merger(this IDictionary<string, string> dictionary, object o, bool nullValueAsKey)
        {
            return dictionary.Merger(o, nullValueAsKey, ECase.NORMAL);
        }

        public static IDictionary<string, object> Merger(this IDictionary<string, object> dictionary, object o, bool nullValueAsKey, ECase keyECase)
        {
            return dictionary.Merger(o, nullValueAsKey, keyECase, false);
        }

        public static IDictionary<string, string> Merger(this IDictionary<string, string> dictionary, object o, bool nullValueAsKey, ECase keyECase)
        {
            return dictionary.Merger(o, nullValueAsKey, keyECase, false);
        }

        public static IDictionary<string, object> Merger(this IDictionary<string, object> dictionary, object o, bool nullValueAsKey, ECase keyECase, bool includeInheritedProperty)
        {
            if (o != null)
            {
                string current;
                if (o is IDictionary<string, object>)
                {
                    IDictionary<string, object> dictionary2 = o as IDictionary<string, object>;
                    using (IEnumerator<string> enumerator = dictionary2.Keys.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            current = enumerator.Current;
                            if (dictionary.ContainsKey(current.ToUpper()))
                            {
                                dictionary[current.ToUpper()] = dictionary2[current];
                            }
                            else
                            {
                                dictionary.Add(current.ToUpper(), dictionary2[current]);
                            }
                        }
                    }
                    return dictionary;
                }
                PropertyInfo[] infoArray = includeInheritedProperty ? o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) : o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (PropertyInfo info in infoArray)
                {
                    current = info.Name;
                    if (keyECase == ECase.UPPER)
                    {
                        current = current.ToUpper();
                    }
                    else if (keyECase == ECase.LOWER)
                    {
                        current = current.ToLower();
                    }
                    object obj2 = info.GetValue(o, null);
                    if (obj2 != null)
                    {
                        if (!dictionary.ContainsKey(current))
                        {
                            dictionary.Add(current, obj2);
                        }
                        else
                        {
                            dictionary[current] = obj2;
                        }
                    }
                    else if (nullValueAsKey)
                    {
                        if (!dictionary.ContainsKey(current))
                        {
                            dictionary.Add(current, null);
                        }
                        else
                        {
                            dictionary[current] = null;
                        }
                    }
                }
            }
            return dictionary;
        }

        public static IDictionary<string, string> Merger(this IDictionary<string, string> dictionary, object o, bool nullValueAsKey, ECase keyECase, bool includeInheritedProperty)
        {
            if (o != null)
            {
                string current;
                if (o is IDictionary<string, string>)
                {
                    IDictionary<string, string> dictionary2 = o as IDictionary<string, string>;
                    using (IEnumerator<string> enumerator = dictionary2.Keys.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            current = enumerator.Current;
                            if (dictionary.ContainsKey(current.ToUpper()))
                            {
                                dictionary[current.ToUpper()] = dictionary2[current];
                            }
                            else
                            {
                                dictionary.Add(current.ToUpper(), dictionary2[current]);
                            }
                        }
                    }
                    return dictionary;
                }
                PropertyInfo[] infoArray = includeInheritedProperty ? o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) : o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (PropertyInfo info in infoArray)
                {
                    current = info.Name;
                    if (keyECase == ECase.UPPER)
                    {
                        current = current.ToUpper();
                    }
                    else if (keyECase == ECase.LOWER)
                    {
                        current = current.ToLower();
                    }
                    object obj2 = info.GetValue(o, null);
                    if (obj2 != null)
                    {
                        if (!dictionary.ContainsKey(current))
                        {
                            dictionary.Add(current, obj2.ToString());
                        }
                        else
                        {
                            dictionary[current] = obj2.ToString();
                        }
                    }
                    else if (nullValueAsKey)
                    {
                        if (!dictionary.ContainsKey(current))
                        {
                            dictionary.Add(current, null);
                        }
                        else
                        {
                            dictionary[current] = null;
                        }
                    }
                }
            }
            return dictionary;
        }

        public static IDictionary<string, object> MergerJson(this IDictionary<string, object> dictionary, string jsonstr)
        {
            return dictionary.MergerJson(jsonstr, false);
        }

        public static IDictionary<string, string> MergerJson(this IDictionary<string, string> dictionary, string jsonstr)
        {
            return dictionary.MergerJson(jsonstr, false);
        }

        public static IDictionary<string, object> MergerJson(this IDictionary<string, object> dictionary, string jsonstr, bool nullValueAsKey)
        {
            return dictionary.MergerJson(jsonstr, nullValueAsKey, ECase.NORMAL);
        }

        public static IDictionary<string, string> MergerJson(this IDictionary<string, string> dictionary, string jsonstr, bool nullValueAsKey)
        {
            return dictionary.MergerJson(jsonstr, nullValueAsKey, ECase.NORMAL);
        }

        public static IDictionary<string, object> MergerJson(this IDictionary<string, object> dictionary, string jsonstr, bool nullValueAsKey, ECase keyECase)
        {
            return dictionary.Merger(JsonAdapter.FromJsonAsDictionary(jsonstr), nullValueAsKey, keyECase);
        }

        public static IDictionary<string, string> MergerJson(this IDictionary<string, string> dictionary, string jsonstr, bool nullValueAsKey, ECase keyECase)
        {
            return dictionary.Merger(JsonAdapter.FromJsonAsDictionary(jsonstr), nullValueAsKey, keyECase);
        }

        public static JsonResult MyJson(this ControllerBase controller, bool flag)
        {
            JsonResult2 result = new JsonResult2();
            result.Data = new { success = flag };
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public static JsonResult MyJson(this ControllerBase controller, object data)
        {
            JsonResult2 result = new JsonResult2();
            result.Data = data;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public static JsonResult MyJson(this ControllerBase controller, bool flag, string msg)
        {
            JsonResult2 result = new JsonResult2();
            result.Data = new { flag = flag, msg = msg };
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public static JsonResult MyJson(this ControllerBase controller, object data, string ContentType)
        {
            JsonResult2 result = new JsonResult2();
            result.Data = data;
            result.ContentType = ContentType;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public static string ObjectToJson<T>(string jsonName, IList<T> IL)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{\"" + jsonName + "\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    PropertyInfo[] properties = Activator.CreateInstance<T>().GetType().GetProperties();
                    builder.Append("{");
                    for (int j = 0; j < properties.Length; j++)
                    {
                        builder.Append(string.Concat(new object[] { "\"", properties[j].Name.ToString(), "\":\"", properties[j].GetValue(IL[i], null), "\"" }));
                        if (j < (properties.Length - 1))
                        {
                            builder.Append(",");
                        }
                    }
                    builder.Append("}");
                    if (i < (IL.Count - 1))
                    {
                        builder.Append(",");
                    }
                }
            }
            builder.Append("]}");
            return builder.ToString();
        }

        public static string Req(this HttpRequestBase requestBase, string key)
        {
            return requestBase.Req(key, string.Empty);
        }

        public static string Req(this HttpRequestBase requestBase, string key, string defaultValue)
        {
            string str = defaultValue;
            if (!string.IsNullOrEmpty(requestBase.Form[key]))
            {
                switch (requestBase.Form[key])
                {
                    case "false":
                        return "0";
                    case "true,false":
                        return "1";
                }
                return requestBase.Form[key];
            }
            if (!string.IsNullOrEmpty(requestBase.QueryString[key]))
            {
                str = requestBase.QueryString[key];
            }
            return str;
        }

        public static void SetPropreryValue(this object o, string propertyName, object value)
        {
            if (o != null)
            {
                o.GetType().GetProperty(propertyName).SetValue(o, value, null);
            }
        }

        public static IEnumerable<T> Sort<T>(this IEnumerable<T> source, string sortDirection, string sortKey)
        {
            sortKey = sortKey.ToUpper();
            Func<T, string> keySelector = delegate(T item)
            {
                IDictionary<string, object> dictionary = null;
                if (item is IDictionary<string, object>)
                {
                    dictionary = item as IDictionary<string, object>;
                }
                else
                {
                    dictionary = item.ToStrObjDict();
                }
                if (dictionary.ContainsKey(sortKey))
                {
                    return Utils.GetString(dictionary[sortKey]);
                }
                return string.Empty;
            };
            return source.Sort<T, string>(sortDirection, keySelector, delegate(string a, string b)
            {
                if (a.IsDateTime() && b.IsDateTime())
                {
                    return Convert.ToDateTime(a).CompareTo(Convert.ToDateTime(b));
                }
                if (a.IsNumeric() && b.IsNumeric())
                {
                    return Convert.ToInt32(a).CompareTo(Convert.ToInt32(b));
                }
                return a.CompareTo(b);
            });
        }

        public static IEnumerable<T> Sort<T, TKey>(this IEnumerable<T> source, string sortDirection, Func<T, TKey> keySelector, Func<TKey, TKey, int> comparerMethod)
        {
            if (sortDirection == "ASC")
            {
                return source.OrderBy<T, TKey>(keySelector, new MyComparer<TKey>(comparerMethod));
            }
            return source.OrderByDescending<T, TKey>(keySelector, new MyComparer<TKey>(comparerMethod));
        }

        public static string ToFormatString(this IDictionary<string, object> dictionary, string format)
        {
            return dictionary.ToFormatString(format, ";");
        }

        public static string ToFormatString(this IDictionary<string, string> dictionary, string format)
        {
            return dictionary.ToFormatString(format, ";");
        }

        public static string ToFormatString(this IEnumerable<StrObjDict> records, string rowSpliter)
        {
            return records.ToFormatString(rowSpliter, "%TEXT%:%VALUE%");
        }

        public static string ToFormatString(this IDictionary<string, object> dictionary, string format, string itemSeparator)
        {
            List<string> list = new List<string>();
            string newValue = "";
            foreach (string str2 in dictionary.Keys)
            {
                if (dictionary[str2] != null)
                {
                    newValue = dictionary[str2].ToString();
                }
                list.Add(format.Replace("%KEY%", str2).Replace("%VALUE%", newValue));
            }
            return string.Join(itemSeparator, list.ToArray());
        }

        public static string ToFormatString(this IDictionary<string, string> dictionary, string format, string itemSeparator)
        {
            List<string> list = new List<string>();
            foreach (string str in dictionary.Keys)
            {
                list.Add(format.Replace("%KEY%", str).Replace("%VALUE%", dictionary[str]));
            }
            return string.Join(itemSeparator, list.ToArray());
        }

        public static string ToFormatString(this IEnumerable<StrObjDict> records, string rowSpliter, string format)
        {
            string str = string.Empty;
            if (records.Count<StrObjDict>() <= 0)
            {
                return str;
            }
            StringBuilder builder = new StringBuilder();
            MatchCollection matchs = new Regex("%([0-9A-Za-z_]*)%").Matches(format);
            List<string> list = new List<string>();
            List<string> list2 = new List<string>();
            string newValue = "";
            foreach (Match match in matchs)
            {
                newValue = match.Groups[1].Value.ToUpper();
                format = format.Replace(match.Groups[1].Value, newValue);
                list2.Add(newValue);
            }
            string item = format;
            foreach (StrObjDict dict in records)
            {
                foreach (string str4 in list2)
                {
                    item = item.Replace("%" + str4 + "%", dict[str4].ToString());
                }
                list.Add(item);
                item = format;
            }
            return string.Join(rowSpliter, list.ToArray());
        }

        public static string ToJson<T, V>(this IDictionary<T, V> dictionary)
        {
            StringBuilder builder = new StringBuilder();
            foreach (T local in dictionary.Keys)
            {
                string str = "";
                if (dictionary[local] != null)
                {
                    str = dictionary[local].ToString();
                }
                builder.AppendFormat(",{0}:\"{1}\"", local.ToString(), str);
            }
            if (builder.Length > 0)
            {
                builder = builder.Remove(0, 1);
            }
            return ("{" + builder.ToString() + "}");
        }

        public static string ToJson(this IEnumerable<StrObjDict> obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength *= 100;
            return serializer.Serialize(obj);
        }

        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength *= 100;
            return serializer.Serialize(obj);
        }

        public static IList<StrObjDict> ToList(this DataTable dt)
        {
            List<StrObjDict> list = new List<StrObjDict>();
            foreach (DataRow row in dt.Rows)
            {
                StrObjDict item = new StrObjDict();
                foreach (DataColumn column in dt.Columns)
                {
                    if (row[column.ColumnName] == DBNull.Value)
                    {
                        item.Add(column.ColumnName.ToUpper(), row[column.ColumnName]);
                    }
                    else
                    {
                        item.Add(column.ColumnName.ToUpper(), row[column.ColumnName]);
                    }
                }
                list.Add(item);
            }
            return list;
        }

        public static List<ListItem> ToListItem(this IList<StrObjDict> records)
        {
            return records.Select<StrObjDict, ListItem>(delegate(StrObjDict record)
            {
                return new ListItem { Text = record["TEXT"].ToString(), Value = (string)record["VALUE"] };
            }).ToList<ListItem>();
        }

        public static List<ListItem> ToListItem(this IList<StrObjDict> records, string textfieldname, string valuefieldname)
        {
            return records.Select<StrObjDict, ListItem>(delegate(StrObjDict record)
            {
                return new ListItem { Text = record.GetFormatValueString(textfieldname), Value = record.GetFormatValueString(valuefieldname) };
            }).ToList<ListItem>();
        }

        public static List<SelectListItem> ToSelectListItem(this IEnumerable<ListItem> objs, string SelectedValue)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (ListItem item in objs)
            {
                SelectListItem item2 = new SelectListItem();
                item2.Text = Utils.GetString(item.Text);
                item2.Value = Utils.GetString(item.Value);
                item2.Selected = Utils.GetString(item.Value) == SelectedValue;
                list.Add(item2);
            }
            return list;
        }

        public static List<SelectListItem> ToSelectListItem(this IEnumerable<StrObjDict> objs, string ITEM_ID, string ITEM_NAME)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (StrObjDict dict in objs)
            {
                SelectListItem item = new SelectListItem();
                item.Text = Utils.GetString(dict[ITEM_NAME]);
                item.Value = Utils.GetString(dict[ITEM_ID]);
                list.Add(item);
            }
            return list;
        }

        public static List<SelectListItem> ToSelectListItem(this IEnumerable<StrObjDict> objs, string ITEM_ID, string ITEM_NAME, string SelectedValue)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (StrObjDict dict in objs)
            {
                SelectListItem item = new SelectListItem();
                item.Text = Utils.GetString(dict[ITEM_NAME]);
                item.Value = Utils.GetString(dict[ITEM_ID]);
                item.Selected = Utils.GetString(dict[ITEM_ID]) == SelectedValue;
                list.Add(item);
            }
            return list;
        }

        public static StrObjDict ToStrObjDict(this object o)
        {
            return StrObjDict.FromVariable(o);
        }

        public static IDictionary<string, object> ToStrObjDict(this object o, bool nullValueAsKey)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            return dictionary.Merger(o, nullValueAsKey);
        }

        public static StrObjDict Union2<T>(this IDictionary<string, object> dictionary1, T dictionary2) where T : IDictionary<string, object>
        {
            StrObjDict dict = new StrObjDict();
            foreach (KeyValuePair<string, object> pair in dictionary1.Union<KeyValuePair<string, object>>(dictionary2))
            {
                dict.Add(pair.Key, pair.Value);
            }
            return dict;
        }

        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
    }
}